package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

public class OtherStudentDao implements BaseStudentDao{
    // 创建集合容器
    private static ArrayList<Student> stus = new ArrayList<>();

    static {
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("itheima-edu-info-manager\\student.txt"));
            byte[] bys = new byte[1024];
            int len = bis.read(bys);
            String stuStr = new String(bys,0,len);
            String[] stuStrArray = stuStr.split(System.lineSeparator());
            for (String s : stuStrArray) {
                String[] split = s.split(",");
                Student student = new Student(split[0],split[1],split[2],split[3]);
                stus.add(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 添加学生方法
    public boolean addStudent(Student stu) {
            stus.add(stu);
            return true;
    }

    // 查看所有学生对象并返回
    public Student[] findAllStudent() {
        Student[] students = new Student[stus.size()];

        for (int i = 0; i < students.length; i++) {
            students[i] = stus.get(i);
        }
        return students;
    }

    //删除学生
    public void deleteStudent(String deleteId) {
        int index = getIndex(deleteId);
        // 调用集合中的remove()方法来实现删除功能
        stus.remove(index);

    }

    public int getIndex(String deleteId) {
        int index = -1;
        for (int i = 0; i < stus.size(); i++) {
            Student stu = stus.get(i);
            if(stu != null && stu.getId().equals(deleteId)){
                index = i;
                break;
            }
        }
        return index;
    }

    public void updateStudent(String updateId, Student newStu) {
        // 1. 查找updateId, 在容器中的索引位置
        int index = getIndex(updateId);
        // 索引位置的数据替换成新的数据
        stus.set(index,newStu);
    }
}
